package com.yhh.member.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhh.common.base.ret.ApiResult;
import com.yhh.common.entity.member.dto.UserDto;
import com.yhh.common.entity.member.model.User;
import com.yhh.common.entity.member.view.UserView;
import com.yhh.common.exception.BusinessException;
import com.yhh.common.jwt.JWTUtil;
import com.yhh.common.utils.FieldsFilter;
import com.yhh.common.utils.RegexUtil;
import com.yhh.member.feign.PhoneServiceFeign;
import com.yhh.member.feign.WeixinServiceFeign;
import com.yhh.member.service.IUserService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 会员服务处理类
 */

@Api(tags = "会员服务API")
@RestController
@RequestMapping("member/api/v1")
@Slf4j
public class MemberController {
    @Autowired
    private PhoneServiceFeign phoneServiceFeign;
    @Autowired
    private IUserService userService;
    @Autowired
    private WeixinServiceFeign weixinServiceFeign;
    /**
     * 发送手机注册码
     * @param phoneNumber
     * @return
     */
    @ApiOperation(value = "发送手机注册码", notes = "开发环境不启用")
    @ApiImplicitParam(value = "手机号码",name = "phoneNumber", required = true,dataType = "String")
    @PostMapping("sendRegCode")
    public ApiResult sendRegCode(String phoneNumber){
        if(!RegexUtil.isMobileExact(phoneNumber)){
            throw new BusinessException("手机号格式不正确");
        }
        if(userService.getOne(new QueryWrapper<User>().eq("phone_number",phoneNumber)) != null){
            throw new BusinessException("手机号已注册");
        }
        return phoneServiceFeign.sendRegCode(phoneNumber);
    }

    @ApiOperation("会员注册")
    @PostMapping("register")
    @ApiImplicitParam(value = "验证码",name = "regCode", required = true,dataType = "String")
    public ApiResult register(@RequestBody @Validated User user, String regCode){

        if(regCode == null || !regCode.matches("\\d{4}")){
            throw new BusinessException("注册码格式不正确");
        }

        if(userService.getOne(new QueryWrapper<User>().eq("phone_number",user.getPhoneNumber())) != null){
            throw new BusinessException("手机号已注册");
        }
        if(userService.getOne(new QueryWrapper<User>().eq("email",user.getEmail())) != null){
            throw new BusinessException("邮箱已注册");
        }
        if(userService.getOne(new QueryWrapper<User>().eq("email",user.getEmail())) != null){
            throw new BusinessException("邮箱已注册");
        }
        ApiResult apiResult = phoneServiceFeign.verifyRegCode(user.getPhoneNumber(), regCode);
        if(apiResult.getCode() != ApiResult.SUCCESS_CODE){
            return apiResult;
        }
        user.setCreateTime(new Date());
        user.setModifyTime(new Date());
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));

        if(!userService.save(user)){
            throw new BusinessException("注册失败，请稍后再试");
        }
        return ApiResult.success("注册成功");
    }

    @GetMapping("callBack")
    @ApiIgnore
    public void callBack(String code, String state, HttpServletResponse response) throws IOException {
        ApiResult result = weixinServiceFeign.getAccessToken(code);
        if(result.getCode() != ApiResult.SUCCESS_CODE){
            throw new BusinessException("code:"+code+",msg:"+result.getMessage());
        }
        String body = result.getResult().get("body").toString();
        //转换成JsonObject
        JSONObject json = JSON.parseObject(body);
        //判断微信用户的OpenId
        String openId = json.getString("openid");
        //判断是否是登录操作
        if(state.equals("login")){
            User user = userService.getOne(new QueryWrapper<User>().eq("open_id", openId));
            if(user == null){
                throw new BusinessException("该微信尚未绑定账号");
            }
            if(user.getStatus() != 1){
                throw new BusinessException("账号被禁用，如有疑问，请联系客服");
            }
            ApiResult ret = JWTUtil.createToken(user);
            if(ret.getCode() == ApiResult.SUCCESS_CODE){
                response.sendRedirect("https://www.baidu.com?token="+ret.getResult().get("token"));
            }
            else{
                response.sendRedirect("login.html");
            }
            return;
        }
        //判断是否是绑定操作
        if(RegexUtil.isMobileExact(code)) {
            if (userService.count(new QueryWrapper<User>().eq("open_id", openId)) > 0) {
                throw new BusinessException("该微信号已绑定其他手机号");
            }
            String accessToken = json.getString("access_token");
            result = weixinServiceFeign.getWXUserinfo(accessToken, openId);
            if (result.getCode() != ApiResult.SUCCESS_CODE) {
                throw new BusinessException("code:" + code + ",msg:" + result.getMessage());
            }
            body = result.getResult().get("body").toString();
            json = JSON.parseObject(body);
            log.info(json.toJSONString());
            String country = new String(json.getString("country").getBytes("ISO_8859_1"), "utf-8");
            String province = new String(json.getString("province").getBytes("ISO_8859_1"), "utf-8");
            String city = new String(json.getString("city").getBytes("ISO_8859_1"), "utf-8");
            String nickname = new String(json.getString("nickname").getBytes("ISO_8859_1"), "utf-8");
            String headimgurl = new String(json.getString("headimgurl").getBytes("ISO_8859_1"), "utf-8");
            String sex = json.getString("sex");

            // 保存微信用户信息
            User user = userService.getOne(new QueryWrapper<User>().eq("phone_number", state));
            user.setName(nickname);
            user.setSex(Integer.valueOf(sex));
            user.setPic(headimgurl);
            user.setOpenId(openId);
            userService.updateById(user);

            response.sendRedirect("https://www.baidu.com");
            return;
        }
    }

    /**
     * 获取微信二维码串
     * @param phoneNumber
     * @return
     */
    @ApiOperation(value="获取微信二维码串")
    @ApiImplicitParam(paramType = "query",value = "手机号", name = "phoneNumber",required = true)
    @GetMapping("getWXQRCode")
    public ApiResult getWXQRCode(String phoneNumber){
        if(!RegexUtil.isMobileExact(phoneNumber)){
            throw new BusinessException("手机号格式不正确");
        }
        if(userService.count(new QueryWrapper<User>().eq("phone_number",phoneNumber)) == 0){
            throw new BusinessException("手机号尚未注册");
        }
        if(userService.count(new QueryWrapper<User>().eq("phone_number",phoneNumber).isNotNull("open_id")) > 0){
            throw new BusinessException("手机号已被其他账号绑定，请先解绑");
        }

        return weixinServiceFeign.getWXQRCode(phoneNumber);
    }

    @ApiOperation(value = "登录")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "手机号", name = "phoneNumber",required = true),
            @ApiImplicitParam(value = "密码", name = "password",required = true)
    })
    @GetMapping("login")
    public ApiResult login(String phoneNumber,String password){
        //1.参数校验
        if(StringUtils.isBlank(phoneNumber) || StringUtils.isBlank(password)){
            return ApiResult.error("账号或密码不能为空");
        }
        //2.验证账号和密码
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone_number",phoneNumber);
        wrapper.eq("password", DigestUtils.md5DigestAsHex(password.getBytes()));
        User user = userService.getOne(wrapper);
        if(user == null){
            return ApiResult.error("账号或密码错误");
        }
        if(user.getStatus() != 1){
            return ApiResult.error("账号已被禁用，如有疑问请联系客服");
        }
        //3.生成token并返回
        return JWTUtil.createToken(user);
    }

    @ApiOperation(value="生成微信登录二维码串")
    @PostMapping("getWXLoginQRCode")
    public ApiResult getWXLoginQRCode(){
        ApiResult login = weixinServiceFeign.getWXQRCode("login");
        return login;
    }
}
